package controller

import (
	"strconv"
	"strings"
	"time"
)

type TimestampConverter struct {
	Base
}

func NewTimestampConverter() *TimestampConverter {
	return &TimestampConverter{}
}

// 时间戳 -> 日期字符串
func (t *TimestampConverter) TimestampToDateTime(timestamp string, format string) string {
	//去除前后空格
	timestamp = strings.TrimSpace(timestamp)
	ts, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return "无效的时间戳"
	}

	// 自动检测毫秒/秒
	if ts > 1e12 { // 毫秒级 (13位)
		ts = ts / 1000
	}

	tm := time.Unix(ts, 0)

	switch format {
	case "RFC3339":
		return tm.Format(time.RFC3339)
	case "YYYY-MM-DD HH:mm:ss":
		return tm.Format("2006-01-02 15:04:05")
	default:
		return tm.Format("2006-01-02 15:04:05")
	}
}

// 日期字符串 -> 时间戳
func (t *TimestampConverter) DateTimeToTimestamp(datetime string) int64 {
	// 设置东八区时区
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		return 0
	}

	layouts := []string{
		"2006-01-02 15:04:05",
		"2006-01-02T15:04:05Z07:00", // RFC3339格式
		"2006-01-02 15:04",
		"2006-01-02",
	}

	for _, layout := range layouts {
		var tm time.Time
		var err error

		// 如果是RFC3339格式（包含时区信息），直接解析
		if layout == "2006-01-02T15:04:05Z07:00" {
			tm, err = time.Parse(layout, datetime)
		} else {
			// 其他格式按照东八区解析
			tm, err = time.ParseInLocation(layout, datetime, loc)
		}

		if err == nil {
			return tm.Unix()
		}
	}
	return 0
}

// 获取当前时间戳
func (t *TimestampConverter) GetCurrentTimestamp() map[string]interface{} {
	now := time.Now()
	return map[string]interface{}{
		"seconds":      now.Unix(),
		"milliseconds": now.UnixMilli(),
		"formatted":    now.Format("2006-01-02 15:04:05"),
	}
}
